﻿using Core.Infrastructures.Cores.DataStore;
using Core.Repositories.Menu.Entities;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;

namespace Core.Repositories.Menu
{
    public partial class MenuRepository: BaseRepository<MenuEntity>, IMenuRepository
    {
        public MenuRepository(
          IDataAccessor dataAccessor)
        {
            _dataAccessor = dataAccessor;
        }

        public override MenuEntity GetById<TKey>(TKey id)
        {
            return _dataAccessor.DbContext.Queryable<MenuEntity>().Mapper((it, cache) =>
            {
                var parents = cache.GetListByPrimaryKeys<MenuEntity>(vmodel => vmodel.ParentId);
                it.Parent = parents.FirstOrDefault(i => i.Id == it.ParentId);
            }).InSingle(id);
        }

        public override IEnumerable<MenuEntity> GetListByPage(Expression<Func<MenuEntity, bool>> expression, string orderBy, int pageIndex, int pageSize, ref int records, ref int totalPage)
        {
            return _dataAccessor.DbContext.Queryable<MenuEntity>().Mapper((it, cache) =>
            {
                var parents = cache.GetListByPrimaryKeys<MenuEntity>(vmodel => vmodel.ParentId);
                it.Parent = parents.FirstOrDefault(i => i.Id == it.ParentId);
            }).Where(expression).OrderByIF(!string.IsNullOrEmpty(orderBy), orderBy).ToPageList(pageIndex, pageSize, ref records, ref totalPage);
        }
    }
}
